//
//  AdsModel.swift
//  Automobile
//
//  Created by erkebulan elzhan on 7/28/20.
//  Copyright © 2020 erkebulan elzhan. All rights reserved.
//

import UIKit


final class AdsHomeModel {
    
    // MARK: - Properties
    
    var delegate: ViewModelProtocol!
    
    var createdAd: Post = Post()
    
    var currentCar: Car?
    
    var currentAds: [Post] = []
    
    var menuIndexPath: IndexPath!
    
    var nextPage: String?
    
    var isMenuHidden = true
    
    let menuItems = [
        MenuPopup.MenuItem(icon: UIImage(named: "edit"), title: "Редактировать"),
        MenuPopup.MenuItem(icon: UIImage(named: "toTop"), title: "Поднять в ТОП"),
        MenuPopup.MenuItem(icon: UIImage(named: "pause"), title: "Остановить")
    ]
    
    private let backendService = Backend()
}


// MARK: - Configuring Posts

extension AdsHomeModel {
    
    func getMyAds (paginate: Bool = false) {
        
        var adRequest: URLRequest!
        
        if paginate {
            adRequest = URLRequest(url: URL(string: nextPage!)!)
        } else {
            adRequest = URLRequest(url: Request(base: .advert).getUrl(path: "adverts/my/"))
        }
        
        delegate.updateSpinner(showSpinner: true)
        
        backendService.fetchFromBackend(for: Response<[Post]>.self, request: adRequest, statusCode: 200) { (result) in
            
            self.delegate.updateSpinner(showSpinner: false)
            
            switch result {
                case .failure(let error):
                    self.delegate.didHappenError(error: error)
                case .success(let response):
                    self.nextPage = response.next
                    self.currentAds = paginate ? self.currentAds + response.results : response.results
                    self.delegate.updatePosts()
            }
        }
    }
    
    func pauseAd (index: Int) {
        let post = currentAds[index]
        var request = URLRequest(url: Request(base: .advert).getUrl(path: "adverts/my/\(post.id)/"))
        request.httpMethod = "PATCH"
        
        self.delegate.updateSpinner(showSpinner: true)
        
        backendService.fetchFromBackend(for: Bool.self, request: request, statusCode: 200, sendBool: true, sendBody: true, body: ["status": ADStatus.archived.rawValue]) { (result) in
            self.delegate.updateSpinner(showSpinner: false)
            switch result {
            case .failure(let err):
                self.delegate.didHappenError(error: err)
            case .success(_):
                self.currentAds[index].status = .archived
                self.delegate.updatePosts()
            }
        }
    }
}

